package com.hx.jeeadminbase.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;

import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @Author: xinmiao.xu
 * @Emial: louis_hsu@yeah.net
 * @CreateDate: 2014年9月26日 下午10:22:06
 * @Description:
 */
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;
    private static SpringUtil stools = null;

    public synchronized static SpringUtil init() {
        if (stools == null) {
            stools = new SpringUtil();
        }
        return stools;
    }

    @Override
    public void setApplicationContext(ApplicationContext arg) throws BeansException {
        context = arg;
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public synchronized static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public synchronized static <T> T getBean(String beanName, Class<T> clazz) { // Object
        return context.getBean(beanName, clazz);
    }

    public static Method[] getBeanMethods(String beanName) {
        try {
            Object bean = getBean(beanName);
            Class<? extends Object> beanClass = bean.getClass();
            Method[] ms = beanClass.getMethods();
            return ms;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取对象指定方法的参数定义
     *
     * @param obj
     * @param method
     * @return Map<paramName, paramType>
     */
    public static Map<String, Object> getMethodDeclareParams(Object obj, String method) {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        Class<?> target = null;
        boolean isAop = AopUtils.isAopProxy(obj); // cglib 或 jdk 代理
        if (isAop) {
            target = AopUtils.getTargetClass(obj);
        } else {
            target = obj.getClass();
        }
        if (target != null) {
            try {
                ClassPool pool = ClassPool.getDefault();
                pool.insertClassPath(new ClassClassPath(target));
                CtClass cc = pool.get(target.getName());
                CtMethod cm = cc.getDeclaredMethod(method);
                // 使用javaassist的反射方法获取方法的参数名
                javassist.bytecode.MethodInfo methodInfo = cm.getMethodInfo();
                CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
                LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
                if (attr == null) {
                    // exception
                    return null;
                }
                int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
                for (int i = 0; i < cm.getParameterTypes().length; i++) {
                    params.put(attr.variableName(i + pos), cm.getParameterTypes()[i]);
                }
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
        }
        return params;
    }

    /**
     * 动态执行bean方法
     *
     * @param beanName
     * @param methodName
     * @param paramTypes
     * @param parameters
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T invokeMethod(String beanName, String methodName, Class<?>[] paramTypes, Object... parameters) {
        try {
            Object bean = getBean(beanName);// ApplicationContextHolder.getBean(beanName);
            Class<? extends Object> beanClass = bean.getClass();
            Method method = null;
            Method[] ms = beanClass.getMethods();
            for (Method m : ms) {
                String mName = m.getName();
                if (StringUtils.equals(methodName, mName)) {
                    boolean isThis = true;
                    Class<?>[] pt = m.getParameterTypes();
                    if (paramTypes.length == pt.length) {
                        int plength = paramTypes.length;
                        if (plength == 0) {
                            isThis = true;
                        } else {
                            for (int i = 0; i < plength; i++) {
                                boolean ff = pt[i].isAssignableFrom(paramTypes[i]);
                                if (!ff) {
                                    isThis = false;
                                    break;
                                }
                            }
                        }
                    } else {
                        isThis = false;
                    }
                    if (isThis) {
                        method = m;
                        break;
                    }
                }
            }
            if (method == null) {
                throw new NoSuchMethodException(beanName + "." + methodName);
            }

            Object obj = null;
            if (parameters == null || parameters.length < 1) {
                obj = method.invoke(bean);
            } else {
                obj = method.invoke(bean, parameters);
            }
            T out = (T) obj;
            return out;
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

}
